// 测试工具：查询鸿蒙平台媒体类型值
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

class MediaTypeTestPage extends StatefulWidget {
  const MediaTypeTestPage({super.key});

  @override
  State<MediaTypeTestPage> createState() => _MediaTypeTestPageState();
}

class _MediaTypeTestPageState extends State<MediaTypeTestPage> {
  List<String> _results = [];
  bool _isLoading = false;

  Future<void> _testMediaTypes() async {
    setState(() {
      _isLoading = true;
      _results = [];
    });

    try {
      // 请求权限
      final PermissionState ps = await PhotoManager.requestPermissionExtend();
      if (ps != PermissionState.authorized) {
        setState(() {
          _results.add('权限未授权: $ps');
          _isLoading = false;
        });
        return;
      }

      // 获取所有资源路径
      final List<AssetPathEntity> paths = await PhotoManager.getAssetPathList(
        type: RequestType.all,
      );

      _results.add('找到 ${paths.length} 个相册');

      // 遍历前几个相册来获取资源信息
      for (int i = 0; i < paths.length && i < 3; i++) {
        final AssetPathEntity path = paths[i];
        // 使用 assetCountAsync 异步获取资源数量
        final int assetCount = await path.assetCountAsync;
        _results.add('相册 ${i + 1}: ${path.name} (资源数: $assetCount)');

        // 获取前5个资源
        final List<AssetEntity> assets = await path.getAssetListRange(
          start: 0,
          end: 5,
        );

        for (final asset in assets) {
          _results.add(
              '  - 资源: ${asset.title ?? "无标题"} | 类型: ${asset.type} | mediaType: ${asset.mimeType ?? '未知'}');
        }
      }
    } catch (e) {
      _results.add('错误: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('媒体类型测试')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _isLoading ? null : _testMediaTypes,
              child: _isLoading
                  ? const CircularProgressIndicator()
                  : const Text('测试媒体类型'),
            ),
            const SizedBox(height: 20),
            Expanded(
              child: ListView.builder(
                itemCount: _results.length,
                itemBuilder: (context, index) {
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(_results[index]),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}